﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Linq;

namespace SuspectPhoto
{
    public class ScreenInfo
    {

        public static double UpLineLimit; //上边界

        public static double DownLineLimit; //下边界

        public static double AspectRatio; //长宽比

        public static int ReSizeScale;  //图像缩放比例

        public static double ScreenScale; //显示区域比例 ：10 就表示实际图像区域比显示区域的各个方向都大10%

        public static readonly string Config_File_Name = "CameraConfig.xml";

        private BackgroundWorker asyncWorker;
        private Action<bool, string> mCallBack;

        private bool mIsLogin;

        private int mLoginId;

        private int mRealPlayId;

        public int LoginId { get { return mLoginId; } }

        public int RealPlayId { get { return mRealPlayId; } }

        public Video Video { get; set; }

        public double TopScale { get; set; }

        public double LeftScale { get; set; }



        public static IList<ScreenInfo> GetScreenInfos()
        {
            IList<ScreenInfo> ss = new List<ScreenInfo>();

            XElement element = XElement.Load(Config_File_Name);

            IEnumerable<XElement> configs = element.Elements("Camera");

            ReSizeScale = Convert.ToInt32(element.Element("ReSizeScale").Value);

            AspectRatio = Convert.ToDouble(element.Element("AspectRatio").Value);

            ScreenScale = Convert.ToDouble(element.Element("ScreenScale").Value);

            UpLineLimit = Convert.ToDouble(element.Element("UpLineLimit").Value);

            DownLineLimit = Convert.ToDouble(element.Element("DownLineLimit").Value);

            foreach (XElement el in configs)
            {
                ScreenInfo si = new ScreenInfo();

                si.IPAddress = el.Attribute("Ip").Value;
                si.Port = (ushort)Convert.ToUInt16(el.Attribute("Port").Value);
                si.User = el.Attribute("User").Value;
                si.Password = el.Attribute("Password").Value;
                si.TopScale = Convert.ToInt32(el.Attribute("TopScale").Value);
                si.LeftScale = Convert.ToInt32(el.Attribute("LeftScale").Value);
                ss.Add(si);
            }

            return ss;
        }

        public static void UpdateCutParameter(string uplimit, string downlimit)
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(Config_File_Name);//加载xml文件，文件
            XmlNode xns = xmlDoc.SelectSingleNode("config");//查找要修改的节点
            XmlNodeList xnl = xns.ChildNodes;//取出所有的子节点
            foreach (XmlNode xn in xnl)
            {
                XmlElement xe = (XmlElement)xn;//将节点转换一下类型
                if (xe.Name == "UpLineLimit")//判断该子节点是否是要查找的节点
                {
                    xe.InnerText = uplimit;//设置新值
                }
                if (xe.Name == "DownLineLimit")
                {
                    xe.InnerText = downlimit;//设置新值
                }
            }
            xmlDoc.Save(Config_File_Name);//保存的该XML文件


            UpLineLimit = Convert.ToDouble(uplimit);

            DownLineLimit = Convert.ToDouble(downlimit);
        }

        public string IPAddress { get; set; }

        public ushort Port { get; set; }

        public string User { get; set; }

        public string Password { get; set; }

        public string ImageFileName { get; set; }

        public ScreenInfo()
        {

        }


        public void Login()
        {
            bool isOnline = false;

            GT_DEV_DEVICECFG devInfo = GT_DEV_DEVICECFG.Init();
            IntPtr devInfoPtr = Marshal.AllocHGlobal(Marshal.SizeOf(devInfo));

            int errCode = 0;

            isOnline = CameraDevice.GT_DEV_Online_Check(IPAddress, Port);

            if (!isOnline)
            {
                mCallBack(false, IPAddress + " 摄像头掉线!");
                return;
            }


            mCallBack(true, "正在连接" + IPAddress + " 摄像头,请等待...");

            mLoginId = CameraDevice.GT_DEV_Login(IPAddress, Port, User, Password, devInfoPtr, ref errCode);

            if (errCode > 0)
            {
                mCallBack(false, IPAddress + " " + GetLoginMsg(errCode));
                return;
            }
            else
            {
                mCallBack(true, IPAddress + " 连接成功!");
            }

            mIsLogin = true;

        }

        public void AsyncPlay(Action<bool, string> callBack)
        {
            this.mCallBack = callBack;

            asyncWorker = new BackgroundWorker();

            asyncWorker.DoWork += (object sender, DoWorkEventArgs e) =>
            {
                Login();
            };
            asyncWorker.RunWorkerCompleted += asyncWorker_RunWorkerCompleted;
            asyncWorker.RunWorkerAsync();

        }

        void asyncWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (mIsLogin)
            {
                mRealPlayId = CameraDevice.GT_DEV_RealPlay(mLoginId, 0, Video.VideoHandle, 0);

                if (mRealPlayId == 0)
                {
                    mCallBack(false, IPAddress + " 视频播放错误!");
                }
                else
                {
                    mCallBack(true, IPAddress + " 视频播放成功!");
                }
            }
        }


        public void Play()
        {
            bool isSuccess = false;

            string msg = null;

            GT_DEV_DEVICECFG devInfo = GT_DEV_DEVICECFG.Init();
            IntPtr devInfoPtr = Marshal.AllocHGlobal(Marshal.SizeOf(devInfo));

            int errCode = 0;

            isSuccess = CameraDevice.GT_DEV_Online_Check(IPAddress, Port);

            if (!isSuccess)
            {
                mCallBack(false, "摄像头掉线!");
                return;
            }

            mLoginId = CameraDevice.GT_DEV_Login(IPAddress, Port, User, Password, devInfoPtr, ref errCode);

            if (errCode > 0)
            {
                msg = GetLoginMsg(errCode);

                mCallBack(false, msg);

                return;
            }

            mRealPlayId = CameraDevice.GT_DEV_RealPlay(mLoginId, 0, Video.VideoHandle, 0);

            if (mRealPlayId == 0)
            {
                mCallBack(false, "视频播放错误!");
                return;
            }

            mCallBack(true, null);
        }

        public bool Logout()
        {
            if (mLoginId <= 0)
            {
                throw new Exception("尚未登录");
            }
            return CameraDevice.GT_DEV_Logout(mLoginId);
        }

        public bool RealPaly()
        {
            mRealPlayId = CameraDevice.GT_DEV_RealPlay(mLoginId, 0, Video.Handle, 0);

            return mRealPlayId > 0 ? true : false;
        }


        private string GetLoginMsg(int err)
        {

            switch (err)
            {
                case 1:
                    return "密码错误";
                case 2:
                    return "用户名错误";
                case 3:
                    return "超时";
                case 4:
                    return "用户已经登录";
                case 5:
                case 6:
                    return "用户名已经失效";
                case 7:
                    return "系统忙";
                case 9:
                    return "你找不到网络服务器";
                default:
                    return null;
            }
        }
    }
}
